package com.base.core.common.utils;

import com.base.core.config.RabbitMQConfig;
import com.base.core.model.CampaignUpdateMessage;
import com.rabbitmq.client.Channel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@Slf4j
public class CampaignMQConsumer {

    @RabbitListener(queues = RabbitMQConfig.CAMPAIGN_QUEUE)
    public void handleCampaignUpdate(CampaignUpdateMessage message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        try {
            // 业务处理
            log.info("收到活动更新消息: {}", message);

            // 模拟处理耗时
            Thread.sleep(1000);

            // 手动ACK确认
            channel.basicAck(tag, false);
        } catch (Exception e) {
            log.error("处理消息异常", e);
            try {
                // 消息重试
                channel.basicNack(tag, false, true);
            } catch (IOException ex) {
                log.error("NACK失败", ex);
            }
        }
    }
}